<template>
    <el-card>
        <el-alert
            title="添加商品信息"
            type="info"
            center
            show-icon
            :closable="false"
        >
        </el-alert>

        <el-steps
            :space="200"
            :active="state.activeIndex - 0"
            finish-status="success"
            align-center
        >
            <el-step title="基本信息"></el-step>
            <el-step title="商品规则"></el-step>
            <el-step title="属性信息"></el-step>
            <el-step title="商品图片"></el-step>
            <el-step title="详情编辑"></el-step>
            <el-step title="完成"></el-step>
        </el-steps>

        <el-form
            :model="state.addForm"
            :rules="state.addFormRules"
            ref="addFormRef"
            label-width="100px"
        >
            <el-tabs v-model="state.activeIndex" :tab-position="'left'">
                <el-tab-pane label="基本信息" name="0">
                    <el-form-item label="供应商" prop="storeId">
                        <el-input
                            disabled
                            placeholder="荷马有限公司"
                        ></el-input>
                    </el-form-item>

                    <el-form-item label="商品类型" prop="productType">
                        <el-input disabled placeholder="普通商品"></el-input>
                    </el-form-item>

                    <el-form-item label="商品类目" prop="cate">
                        <el-cascader
                            v-model="state.addForm.cateId"
                            :options="state.categoryListVOList"
                            :props="state.cateProps"
                            @change="handleCateChange"
                        ></el-cascader>
                    </el-form-item>

                    <el-form-item label="商品名称" prop="productName">
                        <el-input
                            v-model="state.addForm.productName"
                            placeholder="最多输入30个字"
                        ></el-input>
                    </el-form-item>

                    <el-form-item label="商品描述">
                        <el-input
                            v-model="state.addForm.description"
                            placeholder="最多输入60个字"
                        ></el-input>
                    </el-form-item>

                    <el-form-item label="商品品牌">
                        <el-cascader
                            v-model="state.addForm.brandId"
                            :options="state.brandListVOList"
                            :props="state.brandProps"
                        ></el-cascader>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品规则" name="1">
                    <el-form-item
                        label="商品规则："
                        prop="delivery"
                        style="margin-top: 40px"
                    >
                        <el-checkbox
                            label="满99包邮"
                            checked
                            disabled
                        ></el-checkbox>
                    </el-form-item>
                </el-tab-pane>

                <el-tab-pane label="属性信息" name="2">
                    <div>
                        <div class="stand">
                            <ul>
                                <li
                                    class="attr"
                                    v-for="(item, index) in skuData.addForm
                                        .specs"
                                    :key="index"
                                >
                                    <!-- <span @click="remove(index)">删除:</span> -->
                                    <el-button
                                        @click="remove(index)"
                                        type="primary"
                                        style="margin-right: 20px"
                                    >
                                        删除
                                    </el-button>
                                    <el-input
                                        class="title"
                                        v-model="item.specName"
                                        placeholder="请输入属性"
                                        >:</el-input
                                    >

                                    <div
                                        v-if="item.specValues.length"
                                        class="putt"
                                    >
                                        <div
                                            class="putt"
                                            v-for="(subitem,
                                            i) in item.specValues"
                                            :key="i"
                                        >
                                            <el-input
                                                v-model="subitem.value"
                                                placeholder="请输入值"
                                            ></el-input>
                                            <div
                                                class="close"
                                                @click="closeAtrr(index, i)"
                                            >
                                                ×
                                            </div>
                                        </div>
                                    </div>

                                    <div class="append" @click="addAtrr(index)">
                                        +
                                    </div>
                                </li>
                            </ul>
                            <div class="add">
                                <el-button type="primary" @click="addStand"
                                    >添加规格</el-button
                                >
                                <el-button type="primary" @click="getTable"
                                    >生成规格列表</el-button
                                >
                                <el-button type="primary" @click="read" disabled
                                    >读取规格列表</el-button
                                >
                            </div>
                        </div>
                        <!-- <div class="table"> -->
                        <!-- state.addForm.skus -->
                        <el-table
                            v-if="skuData.isTable"
                            :data="skuData.addForm.skus"
                            border
                            style="width: 100%"
                        >
                            <el-table-column label="货号" align="center">
                                <template v-slot="scope">
                                    <el-input
                                        v-model="scope.row.skuCode"
                                    ></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column
                                prop="skuSpecValues"
                                label="sku描述"
                                width="180"
                                align="center"
                            >
                                <template v-slot="scope">
                                    <div
                                        v-for="item in scope.row.skuSpecValues"
                                        :key="item.id"
                                    >
                                        {{ item.spec.specName }}:{{
                                            item.specValue.value
                                        }}
                                    </div>
                                    <!-- {{ scope.row.skuSpecValues[0].spec.specName }} :
                    <el-input
                      v-model="scope.row.skuSpecValues[0].specValue.value"
                      style="width: 80%"
                    ></el-input> -->
                                </template>
                            </el-table-column>
                            <el-table-column
                                label="售卖单价（元）"
                                align="center"
                            >
                                <template v-slot="scope">
                                    <el-input
                                        v-model="scope.row.salePrice"
                                        type="number"
                                    ></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column
                                label="市场价格（元）"
                                align="center"
                            >
                                <template v-slot="scope">
                                    <el-input
                                        v-model="scope.row.listPrice"
                                        type="number"
                                    ></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column label="安全库存" align="center">
                                <template v-slot="scope">
                                    <el-input
                                        v-model="scope.row.safeStockQte"
                                    ></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" align="center">
                                <template v-slot="scope">
                                    <el-button
                                        type="text"
                                        @click.prevent="
                                            deleteRow(
                                                scope.$index,
                                                skuData.addForm.skus
                                            )
                                        "
                                    >
                                        删除
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <!-- </div> -->
                    </div>
                    <!-- <el-form-item
            label="销售属性："
            prop="delivery"
            style="margin-top: 40px"
          >
            <el-button type="primary" @click="state.dialogVisible = true"
              >设置规格</el-button
            >
            <el-button type="text" style="margin-left: 20px" @click="reset">
              清空规格
            </el-button>
          </el-form-item> -->

                    <!-- <el-table
            :data="state.addForm.skus"
            border
            v-if="state.addForm.specs.length > 0"
          >
            <el-table-column label="货号" align="center">
              <template v-slot="scope">
                <el-input v-model="scope.row.skuCode"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="sku描述" align="center" width="400px">
              <template v-slot="scope">
                {{ scope.row.skuSpecValues[0].spec.specName }} :
                <el-input
                  v-model="scope.row.skuSpecValues[0].specValue.value"
                  style="width: 80%"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="售卖单价（元）" align="center">
              <template v-slot="scope">
                <el-input
                  v-model="scope.row.salePrice"
                  type="number"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="市场价格（元）" align="center">
              <template v-slot="scope">
                <el-input
                  v-model="scope.row.listPrice"
                  type="number"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="安全库存" align="center">
              <template v-slot="scope">
                <el-input v-model="scope.row.safeStockQte"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template v-slot="scope">
                <el-button
                  type="text"
                  @click.prevent="deleteRow(scope.$index, state.addForm.skus)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table> -->
                </el-tab-pane>

                <el-tab-pane label="商品图片" name="3">
                    <!-- <el-upload
            class="upload-demo"
            drag
            :action="state.uploadUrl"
            :headers="state.headerObj"
            accept="image/png,image/jpg,image/jpeg"
            multiple
            style="margin: 30px 0 0 30px"
            name="files"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                图片支持格式为png/jpeg/jpg，建议尺寸比例为：1:1
              </div>
            </template>
          </el-upload> -->

                    <el-upload
                        :action="state.uploadUrl"
                        list-type="picture-card"
                        :on-preview="handlePictureCardPreview"
                        :on-remove="handleRemove"
                        name="files"
                        :on-success="handleSuccess"
                        multiple
                        :headers="state.headerObj"
                    >
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog v-model="state.dialogImgVisible">
                        <img width="100%" :src="state.dialogImageUrl" alt="" />
                    </el-dialog>
                </el-tab-pane>
                <el-tab-pane label="详情编辑" name="4">
                    <div ref="editor"></div>
                    <!-- <button @click="syncHTML">同步内容</button> -->
                    <div :innerHTML="content.html"></div>
                    <!-- <el-input v-model="state.addForm.description"></el-input> -->
                    <el-button
                        type="primary"
                        style="margin-top: 15px"
                        @click="add"
                        >新建商品</el-button
                    >
                </el-tab-pane>

                <!-- <el-dialog title="设置规格" v-model="state.dialogVisible" width="60%">
          <el-row style="margin-bottom: 20px">
            <el-col :span="4" style="text-align: center">sku规格</el-col>
            <el-col :span="7" style="text-align: center">规格属性</el-col>
            <el-col :span="6" style="text-align: center">sku规格值</el-col>
          </el-row>
          <el-form :model="state.dialogForm" inline>
            <el-row>
              <el-col :span="5">
                <el-form-item>
                  <el-input v-model="state.dialogForm.specName"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item>
                  <el-select
                    v-model="state.dialogForm.displayType"
                    placeholder="请选择规格属性"
                  >
                    <el-option label="文字" :value="0"></el-option>
                    <el-option label="图片" :value="1"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item>
                  <el-input
                    v-model="state.dialogForm.specValues"
                    style="width: 250px"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="state.dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="handleDialog">
                确 定
              </el-button>
            </span>
          </template>
        </el-dialog> -->
            </el-tabs>
        </el-form>
    </el-card>
</template>

<script>
import { reactive, ref } from "@vue/reactivity";
import {
    getCurrentInstance,
    onMounted,
    onBeforeUnmount
} from "@vue/runtime-core";
import WangEditor from "wangeditor";
import { ElMessage } from "element-plus";

export default {
    setup() {
        const { proxy } = getCurrentInstance();
        const skuData = reactive({
            addForm: {
                skus: [], //tableData
                specs: [] //standData
            },
            input: "",
            isTable: false,
            list: [],
            group: []
        });
        const state = reactive({
            dialogImageUrl: "",
            dialogImgVisible: false,
            activeIndex: "0", //步骤条
            addForm: {
                storeId: 10104,
                productType: "n",
                cateId: "",
                productName: "",
                description: "",
                brandId: "",
                skus: [],
                specs: [],
                protectionIds: [2],
                detailHtml: "",
                expFee: null,
                saleStatus: -1,
                imageUrls: []
            },
            addFormRules: {
                storeId: [{ required: true }],
                productType: [{ required: true }],
                cate: [
                    // { required: true, message: '请选择商品分类', trigger: 'change' },
                ],
                productName: [{ required: true }]
            },
            categoryListVOList: [],
            cateProps: {
                label: "cateName",
                value: "id",
                children: "secondCates",
                expandTrigger: "hover"
            },
            brandListVOList: [],
            brandProps: {
                label: "brandName",
                value: "id"
            },
            dialogVisible: false,
            dialogForm: {
                specName: "",
                displayType: 0,
                specValues: []
            },
            uploadUrl: "/operation/xhr/file/uploads",
            headerObj: {
                "x-auth-token": window.sessionStorage.getItem("token")
            }
        });
        const editor = ref();
        const content = reactive({
            html: "",
            text: ""
        });
        let instance;
        onMounted(() => {
            // getUserInfo()
            findBySupplierId();
            instance = new WangEditor(editor.value);
            instance.config.uploadImgHeaders = {
                "x-auth-token": window.sessionStorage.getItem("token")
            };
            // instance.config.uploadFileName = 'files'
            instance.config.uploadImgServer = "/operation/xhr/file/uploads";
            instance.config.uploadImgTimeout = 10000000;
            instance.config.customUploadImg = async function(files, insert) {
                let formData = new FormData();
                for (var i = 0; i < files.length; i++) {
                    formData.append("files", files[i]);
                }
                const res = await proxy.$http.post(
                    "/operation/xhr/file/uploads",
                    formData
                );
                console.log(res);
                for (let i = 0; i < res.data.data.length; i++) {
                    insert(res.data.data[i]);
                }
            };
            // instance.config.uploadImgHooks = {
            //   customInsert: function (insertImgFn, result) {
            //     for (let i = 0; i < result.data.length; i++) {
            //       insertImgFn(result.data[i])
            //     }
            //   }
            // }
            Object.assign(instance.config, {
                onchange(e) {
                    //   console.log('change', e);
                    state.addForm.detailHtml = e;
                    //   console.log(state.addForm.description)
                }
            });
            instance.create();
        });
        onBeforeUnmount(() => {
            instance.destroy();
            instance = null;
        });
        // const syncHTML = () => {
        //   content.html = instance.txt.html();
        // }
        const add = async () => {
            state.addForm.brandId = state.addForm.brandId[0];
            state.addForm.cateId = state.addForm.cateId[1];
            console.log(state.addForm);

            state.addForm.skus = skuData.addForm.skus;
            state.addForm.specs = skuData.addForm.specs;
            const res = await proxy.$http.post(
                "/operation/xhr/product",
                state.addForm
            );
            console.log(res);
            if (res.data.code == 200) {
                ElMessage({
                    message: "添加商品成功！",
                    type: "success"
                });
                proxy.$router.push("/list");
            }
            ElMessage({
                message: res.data.msg,
                type: "error"
            });
        };
        // const getUserInfo = async () => {
        //   const res = await proxy.$http.get('/operation/xhr/login/user')
        //   console.log(res);
        // }
        const findBySupplierId = async () => {
            const res = await proxy.$http.get(
                "/operation/xhr/supplierInvestment/findBySupplierId?supplierId=10104"
            );
            // console.log(res);
            state.brandListVOList = res.data.data.brandListVOList;
            state.categoryListVOList = res.data.data.categoryListVOList;
            console.log(state.brandListVOList, state.categoryListVOList);
        };
        const handleCateChange = () => {
            console.log(state.addForm);
        };
        const handleDialog = () => {
            // console.log(state.dialogForm);
            state.dialogForm.specValues = state.dialogForm.specValues.split(
                "/"
            );
            state.dialogForm.specValues = state.dialogForm.specValues.map(
                item => {
                    return { value: item, picUrl: null };
                }
            );
            const a = state.dialogForm.specValues.map(item => {
                return {
                    ownerId: "0001",
                    safeStockQte: "",
                    salePrice: "",
                    listPrice: "",
                    skuCode: "",
                    skuSpecValues: [
                        {
                            spec: {
                                specName: state.dialogForm.specName
                            },
                            specValue: {
                                value: item.value
                            }
                        }
                    ]
                };
            });
            console.log(a);
            // console.log(state.dialogForm.specValues)
            // state.addForm.specs = state.dialogForm
            state.addForm.specs.push(state.dialogForm);
            state.tableData = state.dialogForm.specValues;
            state.addForm.skus = a;
            // console.log(state.addForm.specs);
            state.dialogVisible = false;
        };
        const reset = () => {
            console.log(state.addForm);
            state.addForm.skus = [];
        };
        const deleteRow = (index, rows) => {
            rows.splice(index, 1);
        };
        const handlePictureCardPreview = file => {
            console.log(file);
            console.log(file.url);
            state.dialogImageUrl = file.url;
            console.log(state.dialogImageUrl);
            // state.dialogImageUrl = file.response.data[0];
            state.dialogImgVisible = true;
        };
        const handleSuccess = response => {
            state.addForm.imageUrls.push(response.data[0]);
            // console.log(state.addForm);
        };
        const handleRemove = file => {
            console.log(file);
            const filePath = file.response.data[0];
            const i = state.addForm.imageUrls.findIndex(
                x => x.pic === filePath
            );
            state.addForm.imageUrls.splice(i, 1);
            // console.log(state.addForm);
        };

        //属性信息相关方法
        // 添加规格行
        const addStand = i => {
            //  限制规格种类不超过4种
            // if (skuData.addForm.specs.length > 3) {
            //   // this.$message('不能超过四行')
            //   ElMessage({
            //     message: '不能超过四行',
            //     type: 'error'
            //   })
            // } else {
            //   skuData.addForm.specs.push({ specName: '', specValues: [] })
            // }
            skuData.addForm.specs.push({ specName: "", specValues: [] });
        };

        // 删除规格行
        const remove = i => {
            skuData.addForm.specs.splice(i, 1);
        };

        // 添加属性值
        const addAtrr = i => {
            //  限制属性值不超过5个
            // if (skuData.addForm.specs[i].specValues.length > 4) {
            //   // this.$message('不能超过5个')
            //   ElMessage({
            //     message: '不能超过5个',
            //     type: 'error'
            //   })
            // } else {　　　　　　　　// 存的时候是存的对象
            //   skuData.addForm.specs[i].specValues.push({ value: '' })
            // }
            skuData.addForm.specs[i].specValues.push({ value: "" });
        };

        // 删除属性值
        const closeAtrr = (a, b) => {
            skuData.addForm.specs[a].specValues.splice(b, 1);
        };

        const getTable = () => {
            // this.isTable = true
            skuData.isTable = true;
            // this.tableData = []
            skuData.addForm.skus = [];
            // this.group = []
            skuData.group = [];

            // this.list = []
            skuData.list = [];
            //   console.log(this.standData);
            // const num = this.standData.length
            const num = skuData.addForm.specs.length;
            skuData.addForm.specs.forEach(item => {
                skuData.list.push(item.specValues);
            });
            //   console.log(this.list);
            var arr = [];
            var that = skuData;
            function func(skuarr = [], i) {
                for (let j = 0; j < that.list[i].length; j++) {
                    if (i < that.list.length - 1) {
                        skuarr[i] = that.list[i][j].value;
                        func(skuarr, i + 1);
                    } else {
                        arr.push([...skuarr, that.list[i][j].value]);
                    }
                }
                return arr;
            }
            let newList = func([], 0);
            let b;
            let ssv;
            newList.forEach(item => {
                // b = ''
                b = [];
                for (let i = 0; i < num; i++) {
                    // let a = skuData.addForm.specs[i].specName
                    // a = a + ':' + item[i]
                    // //颜色：黑
                    // b = b + a + ';'

                    let a = {
                        spec: {
                            specName: skuData.addForm.specs[i].specName
                        },
                        specValue: {
                            value: item[i]
                        }
                    };
                    b.push(a);
                    // let b = {
                    //   spec: {
                    //     specName: skuData.addForm.specs[i].specName
                    //   },
                    //   specValue: {
                    //     value: item[i]
                    //   }
                    // }
                    // console.log(b);
                }
                skuData.group.push(b);
            });
            // console.log(skuData.group)
            let table = [];
            for (let j = 0; j < skuData.group.length; j++) {
                table.push({
                    // date: skuData.group[j],
                    // name: '',
                    // address: ''
                    ownerId: "0001",
                    salePrice: "",
                    listPrice: "",
                    skuCode: "",
                    skuSpecValues: skuData.group[j]
                });
            }
            // this.tableData = table
            skuData.addForm.skus = table;
            console.log(skuData.addForm);
        };

        return {
            skuData,
            state,
            //富文本编辑器
            // syncHTML,
            editor,
            content,
            //
            add,
            findBySupplierId,
            handleCateChange,
            handleDialog,
            deleteRow,
            reset,
            handlePictureCardPreview,
            handleSuccess,
            handleRemove,
            //属性信息
            addStand,
            remove,
            addAtrr,
            closeAtrr,
            getTable
        };
    }
};
</script>

<style scoped lang="less">
.el-card {
    width: 1440px;
    margin: 50px auto 0;
}
.table,
.stand {
    padding: 40px;
}
.table {
    height: 500px;
}
.add {
    margin-top: 20px;
}
.attr {
    margin-bottom: 10px;
    list-style: none;
}
.el-input {
    width: auto;
}
.putt {
    display: inline-block;
    position: relative;
    margin-right: 10px;
}
.append {
    width: 40px;
    height: 40px;
    background-color: aqua;
    line-height: 40px;
    text-align: center;
    display: inline-block;
    font-size: 28px;
    cursor: pointer;
    vertical-align: middle;
}
.title {
    background-color: bisque;
    margin-right: 10px;
}
.close {
    position: absolute;
    width: 15px;
    height: 15px;
    background-color: burlywood;
    border-radius: 50%;
    line-height: 15px;
    text-align: center;
    right: -5px;
    top: -5px;
}
</style>
